package com.ruangong.GitClient.HunHePanAPI;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class getTab {

    public static String getTabList() {
        String apiUrl = "https://api.hunhepan.com/v1/extab/list_all";
        StringBuilder response = new StringBuilder();

        try {
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                String inputLine;

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

            } else {
                System.out.println("Error in API call, response code: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.toString();
    }
    public static List<Tab> getResult() {
        List<Tab> Tabs= new ArrayList<>();

        String apiResponse = getTab.getTabList();
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(apiResponse, JsonObject.class);
        JsonArray dataArray = jsonObject.getAsJsonArray("data");

        // Extract name and id
        for (JsonElement element : dataArray) {
            JsonObject tabObject = element.getAsJsonObject();
            String name = tabObject.get("name").getAsString();
            int id = tabObject.get("id").getAsInt();
            Tab mytab = new Tab(name, id);
            Tabs.add(mytab);
        }
        return Tabs;
    }
//    public static void main(String[] args) {
//        List<Tab> result = getTab.getResult();
//        System.out.println(result.size());
//        for (Tab tab : result) {
//            System.out.println("Name: " + tab.getName() + ", ID: " + tab.getID());
//        }
//    }
}


